package no14.classtype;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Bar {
	public String a;

	public Bar() {
		System.out.println("default constructor");
	}

	public Bar(String a) {
		this.a = a;
		System.out.println("string constructor");
	}

	public String getA() {
		return a;
	}

	public void setA(String a) {
		this.a = a;
	}

}

public class Reflect {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		try {
			Class<Bar> barClass = (Class<Bar>) Class.forName("no14.Bar");
			// 构造方法
			Constructor<?>[] constructor = barClass.getConstructors();
			Bar bar0 = (Bar) constructor[0].newInstance();
			Bar bar1 = (Bar) constructor[1].newInstance("abc");
			System.out.println(bar0.getA());
			System.out.println(bar1.getA());
			barClass.getMethod("", new Class[]{});
			// 这里是里设置属性的值
			Method m = barClass.getMethod("setA", new Class[] { Class
					.forName("java.lang.String") });
			m.invoke(bar1, new Object[] { "penghao122" });

			// 这里是里获取属性的值
			m = barClass.getMethod("getA", new Class[] {});
			m.invoke(bar1, new Object[] {});

			// 字段名字必须是public才能被查到
			Field f = barClass.getField("a");
			System.out.println(f.getName());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
